import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { hasValidToken } from '@/utils/auth'
import authRoutes from './modules/auth'
import modelRoutes from './modules/model'
import datascreenRoutes from './modules/datascreen'
import customerRoutes from './modules/customer'
import predictionRoutes from './modules/prediction'
import settingsRoutes from './modules/settings'

// 无需权限验证的基础路由
export const constantRoutes = [
  {
    path: '/',
    redirect: '/dashboard',
  },
  {
    path: '/dashboard',
    component: () => import('@/views/layout/AppLayout.vue'),
    redirect: '/dashboard/index',
    children: [
      {
        path: 'index',
        name: 'Dashboard',
        component: () => import('../views/dashboard/DashboardView.vue'),
        meta: {
          title: '仪表盘',
          icon: 'DataLine'
        }
      },
      {
        path: 'analysis',
        name: 'AnalysisDashboard',
        component: () => import('@/views/dashboard/AnalysisDashboard.vue'),
        meta: {
          title: '数据分析看板',
          icon: 'DataLine'
        }
      },
      // 添加模型管理路由
      {
        path: 'models',
        name: 'ModelList',
        component: () => import('../views/models/ModelListView.vue'),
        meta: {
          title: '模型管理',
          icon: 'model',
          requiresAuth: true
        }
      },
      {
        path: 'models/:id',
        name: 'ModelDetail',
        component: () => import('../views/models/ModelDetailView.vue'),
        meta: {
          title: '模型详情',
          requiresAuth: true,
          hidden: true
        }
      }
    ]
  },
  ...authRoutes,
  ...modelRoutes,
  ...datascreenRoutes,
  ...customerRoutes,
  ...predictionRoutes,
  ...settingsRoutes
]

// 需要根据权限动态加载的路由
export const asyncRoutes = [
  // 404页面必须放在最后
  { path: '/:pathMatch(.*)*', redirect: '/404' }
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
  // 平滑滚动
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// 白名单路由（不需要登录即可访问）
const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  // 设置页面标题
  document.title = to.meta?.title ? `${to.meta.title} - 电信客户流失预警系统` : '电信客户流失预警系统'
  
  // 判断用户是否已登录（检查Cookie和localStorage中的token）
  const isLoggedIn = hasValidToken()

  if (isLoggedIn) {
    if (to.path === '/login') {
      // 如果已登录，重定向到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      next()
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 如果在白名单中，直接进入
      next()
    } else {
      // 其他没有访问权限的页面将被重定向到登录页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})

export default router 